package com.enlf.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.enlf.dto.R;
import com.enlf.dto.Result;
import com.enlf.dto.VoucherDTO;
import com.enlf.entity.SeckillVoucher;
import com.enlf.entity.Shop;
import com.enlf.entity.User;
import com.enlf.entity.Voucher;
import com.enlf.service.ISeckillVoucherService;
import com.enlf.service.IShopService;
import com.enlf.service.IVoucherOrderService;
import com.enlf.service.IVoucherService;
import com.enlf.utils.EnlfConstants;
import com.enlf.utils.SystemConstants;
import com.enlf.vo.UserInfoVo;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * _*_ coding : utf-8 _*_
 *
 * @Time : 2024/3/31 11:10
 * @Author : 计201任思伟
 * @File : AdminVoucherController
 * @Project : enjoy-life
 */
@RestController
@RequestMapping("/admin/voucher")
public class AdminVoucherController {
    @Resource
    private IVoucherService voucherService;
    @Resource
    private IVoucherOrderService voucherOrderService;
    @Resource
    private IShopService shopService;

    @Resource
    private ISeckillVoucherService seckillVoucherService;

    public static final DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    /**
     * 新增普通券
     * @param voucher 优惠券信息
     * @return 优惠券id
     */
    @PostMapping("/add")
    public R addVoucher(@RequestBody Voucher voucher) {
        voucherService.save(voucher);
        return R.OK(voucher.getId());
    }

    /**
     * 新增秒杀券
     * @param voucher 优惠券信息，包含秒杀信息
     * @return 优惠券id
     */
    @PostMapping("/addSeckill")
    public R addSeckillVoucher(@RequestBody Voucher voucher) {
        voucherService.addSeckillVoucher(voucher);
        return R.OK(voucher.getId());
    }

    /**
     * 查询店铺的优惠券列表
     * @param shopId 店铺id
     * @return 优惠券列表
     */
    @GetMapping("/list/{shopId}")
    public Result queryVoucherOfShop(@PathVariable("shopId") Long shopId) {
        return voucherService.queryVoucherOfShop(shopId);
    }

    /**
     * 分页查询优惠券信息
     * @param current 页码
     * @return 商铺列表
     */
    @GetMapping("/list")
    public R queryVoucherList(
            @RequestParam(value = "current", defaultValue = "1") Integer current
    ) {
        Page<Voucher> page = voucherService.query()
                .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE_TEN));

        List<VoucherDTO> voucherList = page.getRecords().stream()
                .map(record -> {
                    VoucherDTO voucherDTO = BeanUtil.copyProperties(record, VoucherDTO.class);
                    Shop shopInfo = shopService.getById(record.getShopId());
                    SeckillVoucher seckillVoucher = seckillVoucherService.getById(record.getId());
                    if (null != seckillVoucher){
                        voucherDTO.setBeginTime(seckillVoucher.getBeginTime().format(formatter));
                        voucherDTO.setEndTime(seckillVoucher.getEndTime().format(formatter));
                        voucherDTO.setStock(seckillVoucher.getStock());
                    }
                    voucherDTO.setShopName(shopInfo.getName());
                    return voucherDTO;
                })
                .collect(Collectors.toList());

        Map<String, Object> result = new HashMap<>();
        result.put("total", page.getTotal());
        result.put("list", voucherList);
        return R.OK(result);

    }

    @DeleteMapping("/delete/{id}")
    public R deleteVoucher(@PathVariable("id") Long id) {
        boolean isDelete = voucherService.removeById(id);
        seckillVoucherService.removeById(id);
        if (isDelete) {
            return R.OK();
        }
        return R.FAIL();
    }
    @GetMapping("/info/{id}")
    public R queryVoucher(@PathVariable("id") Long id) {
        Voucher voucher = voucherService.getById(id);
        Shop shop = shopService.getById(voucher.getShopId());
        SeckillVoucher seckillVoucher = seckillVoucherService.getById(voucher.getId());
        VoucherDTO voucherDTO = BeanUtil.copyProperties(voucher, VoucherDTO.class);
        if (null != seckillVoucher){
            voucherDTO.setBeginTime(seckillVoucher.getBeginTime().format(formatter));
            voucherDTO.setEndTime(seckillVoucher.getEndTime().format(formatter));
            voucherDTO.setStock(seckillVoucher.getStock());
        }
        if (null != shop){
            voucherDTO.setShopId(shop.getId());
            voucherDTO.setShopName(shop.getName());
        }
        return R.OK(voucherDTO);

    }

    @PostMapping("/save")
    public R saveVoucher(VoucherDTO voucherDTO) {
        Voucher voucher = BeanUtil.copyProperties(voucherDTO, Voucher.class);
        voucher.setCreateTime(LocalDateTime.now());
        voucherService.save(voucher);
        if (EnlfConstants.ENLF_VOUCHER_TYPE_INT_SECKILL.equals(voucherDTO.getType())){
            SeckillVoucher seckillVoucher = new SeckillVoucher();
            seckillVoucher.setVoucherId(voucher.getId());
            seckillVoucher.setBeginTime(LocalDateTime.parse(voucherDTO.getBeginTime(), formatter));
            seckillVoucher.setEndTime(LocalDateTime.parse(voucherDTO.getEndTime(), formatter));
            seckillVoucher.setUpdateTime(LocalDateTime.now());
            seckillVoucher.setStock(voucherDTO.getStock());
            seckillVoucherService.save(seckillVoucher);
        }
        // 返回
        return R.OK();
    }
    @PutMapping("/update")
    public R updateVoucherById(VoucherDTO voucherDTO) {
        Voucher voucher = BeanUtil.copyProperties(voucherDTO, Voucher.class);
        if (null != voucherDTO.getId()){
            voucherService.updateById(voucher);
        }else {
            voucherService.save(voucher);
        }
        if (EnlfConstants.ENLF_VOUCHER_TYPE_INT_SECKILL.equals(voucherDTO.getType())){
            SeckillVoucher seckillVoucher = new SeckillVoucher();
            seckillVoucher.setVoucherId(voucher.getId());
            seckillVoucher.setBeginTime(LocalDateTime.parse(voucherDTO.getBeginTime(), formatter));
            seckillVoucher.setEndTime(LocalDateTime.parse(voucherDTO.getEndTime(), formatter));
            seckillVoucher.setUpdateTime(LocalDateTime.now());
            seckillVoucher.setStock(voucherDTO.getStock());
            SeckillVoucher seckill = seckillVoucherService.getById(voucher.getId());
            if (null != seckill){
                seckillVoucherService.updateById(seckillVoucher);
            }else {
                seckillVoucherService.save(seckillVoucher);
            }
        }
        // 返回
        return R.OK();
    }

    /**
     * 根据id批量删除用户
     *
     * @param ids
     * @return
     */
    @DeleteMapping(value = "/batch")
    public R batchDelUser(@RequestParam(value = "ids") String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        boolean isSuccess = voucherService.removeByIds(idList);
        seckillVoucherService.removeByIds(idList);
        return isSuccess ? R.OK() : R.FAIL();
    }
}
